package com.lunevich.json.handler;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.lunevich.json.items.ApplicationItem;
import com.lunevich.json.items.PlatformItem;

public class ApplicationXMLHandler extends DefaultHandler {

	private Boolean currentElement = false;
	private String currentValue = "";
	private ApplicationItem applicationItem;
	private ArrayList<ApplicationItem> applicationList = new ArrayList<ApplicationItem>();
	private PlatformItem platformItem;

	public ArrayList<ApplicationItem> getApplicationList() {
		return applicationList;
	}

	// Called when tag starts
	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		currentElement = true;
		currentValue = "";
		if (localName.equals("application")) {
			applicationItem = new ApplicationItem();
		} else if (localName.equals("platform")) {
			platformItem = new PlatformItem();
		} else if (localName.equals("image")) {
			platformItem.setImageUrl(attributes.getValue("url"));
		} 
	}

	// Called when tag closing
	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {

		currentElement = false;

		/** set value */
		if (localName.equalsIgnoreCase("name")) {
			applicationItem.setAppName(currentValue);
		} else if (localName.equalsIgnoreCase("description")) {
			applicationItem.setAppDescription(currentValue);
		} else if (localName.equals("free")) {
			platformItem.setFreeUrl(currentValue);
		} else if (localName.equals("custom_url")) {
			platformItem.setCustomUrl(currentValue);
		} else if (localName.equalsIgnoreCase("application")) {
			applicationItem.setPlatforItem(platformItem);
			applicationList.add(applicationItem);
		}
	}

	// Called to get tag characters
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		if (currentElement) {
			currentValue = currentValue + new String(ch, start, length);
		}
	}
}